GCCPREFIX := riscv64-unknown-elf-
QEMU := qemu-system-riscv64

# gdb
GDB		:= $(GCCPREFIX)gdb
# gcc
CC		:= $(GCCPREFIX)gcc
CFLAGS  := -mcmodel=medany -std=gnu99 -Wno-unused -Werror
CFLAGS	+= -fno-builtin -Wall -O2 -nostdinc $(DEFS)
CFLAGS	+= -fno-stack-protector -ffunction-sections -fdata-sections
CFLAGS  += -g
# ld
LD      := $(GCCPREFIX)ld
LDFLAGS	:= -m elf64lriscv
LDFLAGS	+= -nostdlib --gc-sections
# tools
OBJCOPY := $(GCCPREFIX)objcopy
OBJDUMP := $(GCCPREFIX)objdump

KERN_SRC_DIR := kern
LIBS_SRC_DIR := libs
TOOLS_DIR    := tools

C_SOURCES := $(shell find $(KERN_SRC_DIR) $(LIBS_SRC_DIR) -name "*.c")
S_SOURCES := $(shell find $(KERN_SRC_DIR) $(LIBS_SRC_DIR) -name "*.S")

KERN_DIR := kern
INC_DIR  := libs   
CFLAGS +=  -I$(INC_DIR)				\
		   -I$(KERN_DIR)/driver		\
		   -I$(KERN_DIR)/libs		\
		   -I$(KERN_DIR)/mem		\
		   -I$(KERN_DIR)/trap		\
		   -I$(KERN_DIR)/debug


C_OBJECTS := $(C_SOURCES:.c=.o)
S_OBJECTS := $(S_SOURCES:.S=.o)

ENTRY_OBJECT := $(filter %/entry.o, $(S_OBJECTS))
OTHER_OBJECTS := $(filter-out %/entry.o, $(C_OBJECTS) $(S_OBJECTS))
LINK_OBJECTS := $(ENTRY_OBJECT) $(OTHER_OBJECTS)

LINKER_SCRIPT := $(TOOLS_DIR)/kernel.ld

KERNEL_ELF := kernel.elf
UCOREIMG := ucore.img

all: $(UCOREIMG)

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.S
	$(CC) $(CFLAGS) -c $< -o $@

$(KERNEL_ELF): $(LINK_OBJECTS) $(LINKER_SCRIPT)
	$(LD) $(LDFLAGS) -T $(LINKER_SCRIPT) -o $@ $(LINK_OBJECTS)
	riscv64-unknown-elf-objdump -d kernel.elf > dump.txt

$(UCOREIMG): $(KERNEL_ELF)
	$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@


QEMUFLAGS  := -machine virt 		\
				-bios default		\
				-m 128M -nographic	\
				-device loader,file=$(UCOREIMG),addr=0x80200000

run: $(UCOREIMG)
	$(QEMU) $(QEMUFLAGS) | tee output.log

debug: $(UCOREIMG)
	$(QEMU) $(QEMUFLAGS) -s -S &
	$(GDB) $(KERNEL_ELF) -ex "target remote localhost:1234"

clean:
	rm -f $(C_OBJECTS) $(S_OBJECTS) $(KERNEL_ELF) $(UCOREIMG) dump.txt output.log

qemu_test:
	qemu-system-riscv64 \
		-machine virt 	\
		-m 128M			\
		-bios default	\
		-device loader,file=ucore.img,addr=0x80200000